package cn.zjxiliu.lib_config;

import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by jessie on 2018/10/27.
 */

public class AssertsResUtils {

    public static InputStream getConfigInputStream(Context context, @NonNull String configName) throws IOException {
        AssetManager assetManager = context.getAssets();
        String[] fileNames = assetManager.list("");
        if (fileNames != null && fileNames.length > 0) {
            for (String fileName : fileNames) {
                if (configName.equalsIgnoreCase(fileName)) {
                    return assetManager.open(fileName, AssetManager.ACCESS_BUFFER);
                }
            }
        }
        throw new ConfigParserException(
                ConfigParserException.CAN_NOT_FIND_CONFIG_FILE);
    }


    public static Properties getConfigProperties(Context context, @NonNull String configName) throws IOException {
        AssetManager assetManager = context.getAssets();
        String[] fileNames = assetManager.list("");
        if (fileNames != null && fileNames.length > 0) {
            for (String fileName : fileNames) {
                if (configName.equalsIgnoreCase(fileName)) {
                    Properties properties = new Properties();
                    properties.load(context.getAssets().open(fileName));
                    return properties;
                }
            }
        }
        throw new ConfigParserException(
                ConfigParserException.CAN_NOT_FIND_CONFIG_FILE);
    }


    public static ParserType getConfigParserTypeByName(Context context, String configSimpleName) {
        try {
            AssetManager assetManager = context.getAssets();
            String[] fileNames = assetManager.list("");
            if (fileNames != null && fileNames.length > 0) {
                for (String fileName : fileNames) {
                    String[] item = fileName.split("\\.");
                    if(item.length == 2){
                        if(item[0].equalsIgnoreCase(configSimpleName)){
                            if(item[1].equalsIgnoreCase("xml")){
                                return ParserType.TYPE_XML;
                            }else if(item[1].equalsIgnoreCase("properties")){
                                return ParserType.TYPE_PROPERTIES;
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new ConfigParserException(
                    ConfigParserException.IO_EXCEPTION);
        }
        throw new ConfigParserException(
                ConfigParserException.CAN_NOT_FIND_CONFIG_FILE);
    }
}
